package com.Action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import transformFactory.OperateImage;

import com.Entity.Club;
import com.Entity.DoctorInfo;
import com.Entity.Favoritetopic;
import com.Entity.Topic;
import com.Entity.Topicclassify;
import com.Entity.Topiccomment;
import com.Entity.Userdata;
import com.Entity.Users;
import com.Entity.Page.Page;
import com.Service.ClubService;
import com.Service.DoctorInfoService;
import com.Service.FavoriteTopicService;
import com.Service.TopicClassifyService;
import com.Service.TopicCommentService;
import com.Service.TopicService;
import com.Service.UserdataService;
import com.Service.UsersService;
import com.alibaba.fastjson.JSON;

public class ClubAction  extends BaseAction{
	
	private static final Logger logger = Logger.getLogger(ClubAction.class);
	private static final String ERRO="erro";
	
	private int clubid=0;
	private long topicid=0;
	
	private File upload;  //文件
	private String uploadContentType;  //文件类型
	private String uploadFileName;   //文件名

	@Autowired
	private ClubService clubService;
	@Autowired
	private TopicService topicService;
	@Autowired
	private TopicClassifyService topicClassifyService;
	@Autowired
	private TopicCommentService topicCommentService;
	@Autowired
	private UsersService usersservice;
	@Autowired
	private UserdataService userdataservice;
	@Autowired
	private FavoriteTopicService favoriteTopicService;
	@Autowired
	private DoctorInfoService doctorInfoService;
	
	Club club=new Club();
	Topic topic=new Topic();
	Users topicuser=new Users();
	Users commentuser=new Users();
	Topiccomment topiccomment=new Topiccomment();
	Userdata userdata=new Userdata();
	Userdata commentuserdata=new Userdata();
	Page pagebean=new Page();
	Favoritetopic favoritetopic=new Favoritetopic();
	DoctorInfo doctorinfo=new DoctorInfo();
	
	List<Topicclassify> topicClassifyList=new ArrayList<Topicclassify>();
	List<Topic> topiclist=new ArrayList<Topic>();
	List<Topiccomment> topiccommentlist=new ArrayList<Topiccomment>();
	List<Users> commentuserlist=new ArrayList<Users>();
	List<Users> topicuserlist=new ArrayList<Users>();
	List<Userdata> commentuserdatalist=new ArrayList<Userdata>();
	List<Favoritetopic> favoritetopiclist=new ArrayList<Favoritetopic>();
	List<DoctorInfo> doctorlist=new ArrayList<DoctorInfo>();
	List topicnumlist=new ArrayList();
	
	HttpSession session = ServletActionContext.getRequest().getSession();
	Users user=(Users) session.getAttribute("temploginbean");
	
	Map queryparammap=new HashMap();
	//封装获取参数的方法
	private void getParams(){
		
		String str_page=ServletActionContext.getRequest().getParameter("page");
		String str_rows=ServletActionContext.getRequest().getParameter("rows");
		String str_topicClassifyId=ServletActionContext.getRequest().getParameter("topicClassifyId");
		String str_orderflag=ServletActionContext.getRequest().getParameter("orderflag");
		String doctorid=ServletActionContext.getRequest().getParameter("docid");
		
		if(str_page!=null&&!str_page.equals("")&&!str_page.equals("0")){
			pagebean.setCurrpage(Integer.parseInt(str_page));
		}
		if(str_rows!=null&&!str_rows.equals("")&&!str_rows.equals("0")){
			pagebean.setRows(Integer.parseInt(str_rows));
		}
		if(str_topicClassifyId!=null&&!str_topicClassifyId.equals("")&&!str_topicClassifyId.equals("0")){
			pagebean.setTopicClassifyId(Integer.parseInt(str_topicClassifyId));
		}
		if(str_orderflag!=null&&!str_orderflag.equals("")&&!str_orderflag.equals("0")){
			pagebean.setOrderflag(Integer.parseInt(str_orderflag));
		}
		if(doctorid!=null&&!doctorid.equals("")&&!doctorid.equals("0")){
			doctorinfo=this.doctorInfoService.getById(Integer.parseInt(doctorid));
		}
	}
	
	
	
	/***********************************************医院圈 专有函数********************************************************/
	/**
	 * 选择医院进入医院圈
	 * @return
	 * @throws Exception
	 */
	public String selectHos() throws Exception{
		clubid=Integer.parseInt(ServletActionContext.getRequest().getParameter("clubid"));
		this.getParams();
		club=this.clubService.getById(clubid);
		doctorlist=doctorInfoService.findByHosId(clubid,pagebean.getCurrpage(),pagebean.getRows());
		if(doctorlist.size()>0){
			for(int i=0;i<doctorlist.size();i++){
				topicnumlist.add(this.topicService.countDocTopic(clubid, doctorlist.get(i).getDoctorId(), pagebean.getTopicClassifyId()));
			}
		}
		return "findHosSucc";
	}
	
	/***********************************************通用********************************************************/
	/**
	 * 选择圈子模块
	 */
	public String selectClub() throws Exception{
		
		clubid=Integer.parseInt(ServletActionContext.getRequest().getParameter("clubid"));
		
		if(clubid!=0){
			this.getParams();
			/**********************************医院圈**************************************************/
			if(doctorinfo.getDoctorId()!=null&&doctorinfo.getDoctorId()>0){
				pagebean.setTotalrecords(topicService.countDocTopic(clubid,doctorinfo.getDoctorId(), pagebean.getTopicClassifyId()));
				topiclist=topicService.getDocTopicList(clubid,doctorinfo.getDoctorId(),pagebean.getTopicClassifyId(),pagebean.getOrderflag(),pagebean.getCurrpage(),pagebean.getRows());
				pagebean.setTotalpage((int) Math.ceil((double)pagebean.getTotalrecords()/(double)pagebean.getRows()));
				topicClassifyList=this.topicClassifyService.find();
				
				if(topiclist.size()!=0){
					
					for(int i=0;i<topiclist.size();i++){
						topicuser=this.usersservice.getById(topiclist.get(i).getTopicAuthorId());
						this.topicuserlist.add(topicuser);
					}
				}
			}
			/**********************************同龄圈**************************************************/
			else{
				//如果topicClassifyId不为0，则根据分类获取帖子列表
				if(pagebean.getTopicClassifyId()>0){
					pagebean.setTotalrecords(topicService.countTopicByTopicClassifyId(clubid, pagebean.getTopicClassifyId()));
					topiclist=topicService.getTopicListByTopicClassifyId(clubid,pagebean.getTopicClassifyId(),pagebean.getOrderflag(),pagebean.getCurrpage(),pagebean.getRows());
				}
				else{
					pagebean.setTotalrecords(topicService.countTopicByClubId(clubid));
					topiclist=topicService.getTopicListByClubId(clubid,pagebean.getOrderflag(),pagebean.getCurrpage(),pagebean.getRows());
				}
				
				pagebean.setTotalpage((int) Math.ceil((double)pagebean.getTotalrecords()/(double)pagebean.getRows()));
				topicClassifyList=this.topicClassifyService.find();
				
				if(topiclist.size()!=0){
					
					for(int i=0;i<topiclist.size();i++){
						topicuser=this.usersservice.getById(topiclist.get(i).getTopicAuthorId());
						this.topicuserlist.add(topicuser);
					}
				}
			}
			
			club=this.clubService.getById(clubid);
			return "selectClubSucc";
		}
		return ERRO;
	}

	/**
	 * 点击发表新帖传递圈子的参数，初始化发表新帖页面帖子分类列表等信息
	 * @return
	 * @throws Exception
	 */
	public String initAddTopic() throws Exception{
		
		clubid=Integer.parseInt(ServletActionContext.getRequest().getParameter("clubid"));
		this.getParams();
		club=this.clubService.getById(clubid);
		topicClassifyList=this.topicClassifyService.find();
		return "initAddTopicSucc";
	}
	
	/**
	 * 发表新帖
	 * @return
	 * @throws Exception
	 */
	public String addTopic() throws Exception{
		
		/*
		 * 上传图片的处理
		 * 获取当前用户ID，用于创建保存用户图片、文件的路径
		 */
       // Users user= (Users) ServletActionContext.getRequest().getSession().getAttribute("temploginbean");
        /**
         * 将文件保存到项目目录下  
         */
        String uploadPath;
		String fileName;
		String path = ServletActionContext.getRequest().getContextPath();
		String basePath = ServletActionContext.getRequest().getScheme()+"://"+ServletActionContext.getRequest().getServerName()+":"+ServletActionContext.getRequest().getServerPort()+path+"/";
		
		//logger.info("path:"+path+"-"+"basePath:"+basePath);
		
		if(upload!=null && uploadContentType!=null && uploadFileName!=null){
		try {
			
			InputStream is = new FileInputStream(upload);
			//uploadPath = ServletActionContext.getServletContext().getRealPath("\\images\\clubUpload_img")+"\\"+topic.getTopicAuthorId()+"\\topicImg";
			uploadPath = ServletActionContext.getServletContext().getRealPath("/")+"clubUpload_img";
			
			Properties pro = System.getProperties();
			String osName = pro.getProperty("os.name");//获得当前操作系统的名称

			if("Linux".equals(osName) || "linux".equals(osName) || "LINUX".equals(osName)){
				uploadPath = session.getServletContext().getRealPath("/")+"/clubUpload_img"; //linux环境下的路径
			}
			
			File dirFile = new File(uploadPath);
			// 判断当前文件夹（路径）是否存在，如果不存在则创建
	        if (!dirFile.exists()) {
	        	//dirFile.mkdirs();
	        	dirFile.mkdir();
	        }
	        //为文件重命名
			fileName = java.util.UUID.randomUUID().toString();
			fileName += uploadFileName.substring(uploadFileName.length() - 4);  
			File toFile = new File(uploadPath, fileName);
			
			//logger.info("图片存入本地的路径="+uploadPath+"\\"+fileName);
			OutputStream os = new FileOutputStream(toFile);
			byte[] buffer = new byte[1024];
			int length = 0;  
			while ((length = is.read(buffer)) > 0) {
				os.write(buffer, 0, length);     
			}     
			is.close();
			os.close();
			
			String srcImagePath=uploadPath+"/"+fileName;
			String toImagePath=uploadPath+"/"+fileName;

			OperateImage operateimage=new OperateImage();
			operateimage.reduceImageEqualProportion(srcImagePath, toImagePath, 1);
			
			//logger.info("图片存数据库的路径="+"images/clubUpload_img/"+topic.getTopicAuthorId()+fileName);
			//topic.setTopicImageUrl(basePath+"images/clubUpload_img/"+topic.getTopicAuthorId()+"/topicImg/"+fileName);
			topic.setTopicImageUrl(basePath+"clubUpload_img/"+fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}  
		} 
		
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		topic.setCommentNumber(0);
		topic.setIsClassical(0);
		topic.setScanNumber(0);
		topic.setFavoriteNumber(0);
		topic.setTopicCreatedTime(nowtime);	
		
		//判断，如果是医院圈的帖子，则要存储医生的ID,返回医生的信息
		if(doctorinfo.getDoctorId()!=null&&doctorinfo.getDoctorId()>0){
			topic.setDoctorId(doctorinfo.getDoctorId());
			doctorinfo=this.doctorInfoService.getById(doctorinfo.getDoctorId());
		}
		else{
			topic.setDoctorId(0);
		}
		
		this.topicService.save(topic);
		
		club=this.clubService.getById(topic.getClubCategoryId());
		topicuser=this.usersservice.getById(topic.getTopicAuthorId());
		
		pagebean.setTotalrecords(1L);
		pagebean.setTotalpage((int) Math.ceil((double)pagebean.getTotalrecords()/(double)pagebean.getRows()));
		
		return "addTopicSucc";
	}
	
	/*
	 * 看某篇帖子及其评论
	 */
	public String reviewTopic()throws Exception{
			topicid=Long.parseLong(ServletActionContext.getRequest().getParameter("topicid"));
			this.getParams();		
			pagebean.setTotalrecords(topicCommentService.countTotalCommentByTopicId(topicid));
			pagebean.setTotalpage((int) Math.ceil((double)pagebean.getTotalrecords()/(double)pagebean.getRows()));
			
			topic=topicService.getById(topicid);
			topic.setScanNumber(topic.getScanNumber()+1);
			this.topicService.update(topic);
			topicuser=this.usersservice.getById(topic.getTopicAuthorId());
			userdata=this.userdataservice.getById(topic.getTopicAuthorId());
			club=this.clubService.getById(topic.getClubCategoryId());
			topiccommentlist=topicCommentService.getTopicCommentByTopicId(topicid,pagebean.getCurrpage(),pagebean.getRows());
			
			if(topiccommentlist.size()!=0){
				for(int i=0;i<topiccommentlist.size();i++){
					commentuser = this.usersservice.getById(topiccommentlist.get(i).getCommentAuthorId());
					commentuserdata=this.userdataservice.getById(topiccommentlist.get(i).getCommentAuthorId());
					this.commentuserlist.add(commentuser);
					this.commentuserdatalist.add(commentuserdata);
				}
			}
			//判断是否已收藏此帖
			boolean favoriteflag=this.favoriteTopicService.getFavorited(user.getUserId(), topicid);
			ServletActionContext.getRequest().setAttribute("favoriteflag", favoriteflag);
			return "reviewTopicSucc";
		}
	
	
	/**
	 * 帖子评论翻页
	 * @return
	 * @throws Exception
	 */
	public String topicCommentPageClassify()throws Exception{
 		
		topicid=Long.parseLong(ServletActionContext.getRequest().getParameter("topicid"));
		this.getParams();
		
		pagebean.setTotalrecords(topicCommentService.countTotalCommentByTopicId(topicid));
		pagebean.setTotalpage((int) Math.ceil((double)pagebean.getTotalrecords()/(double)pagebean.getRows()));
		
		topic=topicService.getById(topicid);
		this.topicService.update(topic);
		topicuser=this.usersservice.getById(topic.getTopicAuthorId());
		userdata=this.userdataservice.getById(topic.getTopicAuthorId());
		club=this.clubService.getById(topic.getClubCategoryId());
		topiccommentlist=topicCommentService.getTopicCommentByTopicId(topicid,pagebean.getCurrpage(),pagebean.getRows());
		
		if(topiccommentlist.size()!=0){
			for(int i=0;i<topiccommentlist.size();i++){
				commentuser = this.usersservice.getById(topiccommentlist.get(i).getCommentAuthorId());
				commentuserdata=this.userdataservice.getById(topiccommentlist.get(i).getCommentAuthorId());
				this.commentuserlist.add(commentuser);
				this.commentuserdatalist.add(commentuserdata);
			}
		}
		return "reviewTopicSucc";
	}
	
	
	/*
	 * 评论帖子
	 */
	public String addTopicComment()throws Exception{
		
		Date date=new Date();
		//更新帖子评论数、最新评论者及时间
		topic=this.topicService.getById(topiccomment.getOriginalTopicId());
		
		Long totalCommentNum=topicCommentService.countTotalCommentByTopicId(topiccomment.getOriginalTopicId());
		pagebean.setTotalrecords(totalCommentNum);
		pagebean.setTotalpage((int) Math.ceil((double)pagebean.getTotalrecords()/(double)pagebean.getRows()));
		
		topic.setCommentNumber(this.topicService.getById(topiccomment.getOriginalTopicId()).getCommentNumber()+1);
		topic.setLatestCommentUserName(this.usersservice.getById(topiccomment.getCommentAuthorId()).getUserName());
		topic.setLatestCommentTime(date);
		this.topicService.update(topic);
		topiccomment.setCommentTime(date);
		topiccomment.setFloorNum((int) (totalCommentNum+1));
		this.topicCommentService.save(topiccomment);
		/*
		 * 保存帖子的评论信息后要返回帖子的所有信息
		 */
		topicuser=this.usersservice.getById(topic.getTopicAuthorId());
		userdata=this.userdataservice.getById(topic.getTopicAuthorId());
		club=this.clubService.getById(topic.getClubCategoryId());
		
		//如果是医院圈则要返回医生的信息
		if(doctorinfo.getDoctorId()!=null&&doctorinfo.getDoctorId()>0){
			doctorinfo=this.doctorInfoService.getById(doctorinfo.getDoctorId());
		}
		
		topiccommentlist=topicCommentService.getTopicCommentByTopicId(topic.getTopicId(),1,10);
		if(topiccommentlist.size()!=0){
			for(int i=0;i<topiccommentlist.size();i++){
				commentuser = this.usersservice.getById(topiccommentlist.get(i).getCommentAuthorId());
				commentuserdata=this.userdataservice.getById(topiccommentlist.get(i).getCommentAuthorId());
				this.commentuserlist.add(commentuser);
				this.commentuserdatalist.add(commentuserdata);
			}
		}
		return "reviewTopicSucc";
	}
	
	/**
	 * 初始化回复跟帖页面
	 */
	public String initTopicCommentReply() throws Exception{
		//如果是医院圈则要返回医生的信息
		if(doctorinfo.getDoctorId()>0){
			doctorinfo=this.doctorInfoService.getById(doctorinfo.getDoctorId());
		}
		return "initTopicCommentReplySucc";
	}
	
	/**
	 * 
	 * 收藏帖子
	 * 	 * @return
	 */
	public void addFavoriteTopic() throws Exception{
		topicid=Long.parseLong(ServletActionContext.getRequest().getParameter("topicid"));
		this.favoritetopic.setTopicId(topicid);
		this.favoritetopic.setUserId(user.getUserId());
		//time
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		this.favoritetopic.setFavoriteTime(nowtime);
		this.favoriteTopicService.save(favoritetopic);
		//更新帖子的收藏数
		topic=this.topicService.getById(topicid);
		topic.setFavoriteNumber(topic.getFavoriteNumber()+1);
		this.topicService.update(topic);
	}
	
	/**
	 * 
	 * 获取已收藏帖子的列表
	 * @return
	 */
	public String getFavoriteTopicList() throws Exception{
		this.getParams();
		pagebean.setTotalrecords(favoriteTopicService.countFavoriteTopicByUserId(user.getUserId()));
		pagebean.setTotalpage((int) Math.ceil((double)pagebean.getTotalrecords()/(double)pagebean.getRows()));
		
		favoritetopiclist=this.favoriteTopicService.getFavoriteTopicList(user.getUserId(), pagebean.getCurrpage(),pagebean.getRows());
		if(favoritetopiclist.size()>0){
			for(int i=0;i<favoritetopiclist.size();i++){
				this.topic=this.topicService.getById(favoritetopiclist.get(i).getTopicId());
				this.topiclist.add(topic);
			}
		}
		return "getFavoriteTopicListSucc";
	}
	
	/**
	 * 取消收藏
	 * @return
	 */
	public String cancelFavoriteTopic() throws Exception{
		int favoritetopicid=Integer.parseInt(ServletActionContext.getRequest().getParameter("favoritetopicid"));
		this.getParams();
		favoritetopic=favoriteTopicService.getById(favoritetopicid);
		this.favoriteTopicService.delete(favoritetopic);
		//更新帖子的收藏数
		topic=this.topicService.getById(favoritetopic.getTopicId());
		topic.setFavoriteNumber(topic.getFavoriteNumber()-1);
		this.topicService.update(topic);
		
		pagebean.setTotalrecords(favoriteTopicService.countFavoriteTopicByUserId(user.getUserId()));
		pagebean.setTotalpage((int) Math.ceil((double)pagebean.getTotalrecords()/(double)pagebean.getRows()));
		
		favoritetopiclist=this.favoriteTopicService.getFavoriteTopicList(user.getUserId(), pagebean.getCurrpage(),pagebean.getRows());
		if(favoritetopiclist.size()>0){
			for(int i=0;i<favoritetopiclist.size();i++){
				this.topic=this.topicService.getById(favoritetopiclist.get(i).getTopicId());
				this.topiclist.add(topic);
			}
		}
		return "getFavoriteTopicListSucc";
	}
	
	
	
	public Club getClub() {
		return club;
	}


	public void setClub(Club club) {
		this.club = club;
	}


	public Topic getTopic() {
		return topic;
	}

	public void setTopic(Topic topic) {
		this.topic = topic;
	}

	
	public Topiccomment getTopiccomment() {
		return topiccomment;
	}


	public void setTopiccomment(Topiccomment topiccomment) {
		this.topiccomment = topiccomment;
	}


	public Users getTopicuser() {
		return topicuser;
	}


	public void setTopicuser(Users topicuser) {
		this.topicuser = topicuser;
	}


	public Users getCommentuser() {
		return commentuser;
	}

	public void setCommentuser(Users commentuser) {
		this.commentuser = commentuser;
	}
	

	public List<Users> getTopicuserlist() {
		return topicuserlist;
	}


	public void setTopicuserlist(List<Users> topicuserlist) {
		this.topicuserlist = topicuserlist;
	}


	public Userdata getUserdata() {
		return userdata;
	}

	public void setUserdata(Userdata userdata) {
		this.userdata = userdata;
	}
	
	public Userdata getCommentuserdata() {
		return commentuserdata;
	}


	public void setCommentuserdata(Userdata commentuserdata) {
		this.commentuserdata = commentuserdata;
	}


	public List<Topicclassify> getTopicClassifyList() {
		return topicClassifyList;
	}

	public void setTopicClassifyList(List<Topicclassify> topicClassifyList) {
		this.topicClassifyList = topicClassifyList;
	}
	
	public List<Topic> getTopiclist() {
		return topiclist;
	}

	public void setTopiclist(List<Topic> topiclist) {
		this.topiclist = topiclist;
	}

	public List<Topiccomment> getTopiccommentlist() {
		return topiccommentlist;
	}

	public void setTopiccommentlist(List<Topiccomment> topiccommentlist) {
		this.topiccommentlist = topiccommentlist;
	}


	public List<Users> getCommentuserlist() {
		return commentuserlist;
	}


	public void setCommentuserlist(List<Users> commentuserlist) {
		this.commentuserlist = commentuserlist;
	}


	public List<Userdata> getCommentuserdatalist() {
		return commentuserdatalist;
	}


	public void setCommentuserdatalist(List<Userdata> commentuserdatalist) {
		this.commentuserdatalist = commentuserdatalist;
	}


	public Page getPagebean() {
		return pagebean;
	}


	public void setPagebean(Page pagebean) {
		this.pagebean = pagebean;
	}
	
	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public int getClubid() {
		return clubid;
	}

	public void setClubid(int clubid) {
		this.clubid = clubid;
	}

	public long getTopicid() {
		return topicid;
	}

	public void setTopicid(long topicid) {
		this.topicid = topicid;
	}

	public Users getUser() {
		return user;
	}

	public void setUser(Users user) {
		this.user = user;
	}

	public Favoritetopic getFavoritetopic() {
		return favoritetopic;
	}

	public void setFavoritetopic(Favoritetopic favoritetopic) {
		this.favoritetopic = favoritetopic;
	}

	public List<Favoritetopic> getFavoritetopiclist() {
		return favoritetopiclist;
	}

	public void setFavoritetopiclist(List<Favoritetopic> favoritetopiclist) {
		this.favoritetopiclist = favoritetopiclist;
	}
	public List<DoctorInfo> getDoctorlist() {
		return doctorlist;
	}
	public void setDoctorlist(List<DoctorInfo> doctorlist) {
		this.doctorlist = doctorlist;
	}
	public DoctorInfo getDoctorinfo() {
		return doctorinfo;
	}
	public void setDoctorinfo(DoctorInfo doctorinfo) {
		this.doctorinfo = doctorinfo;
	}



	public List getTopicnumlist() {
		return topicnumlist;
	}



	public void setTopicnumlist(List topicnumlist) {
		this.topicnumlist = topicnumlist;
	}
	
}
